package com.centit.framework.ip.templateFile.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.centit.framework.common.JsonResultUtils;
import com.centit.framework.common.ResponseMapData;
import com.centit.framework.core.controller.BaseController;
import com.centit.framework.ip.templateFile.po.TemplateFile;
import com.centit.framework.ip.templateFile.service.TemplateFileManager;
import com.centit.framework.ip.util.layuiResultUtil;
import com.centit.framework.system.po.DataDictionary;
import com.centit.framework.system.service.DataDictionaryManager;
import com.centit.support.algorithm.UuidOpt;
import com.centit.support.database.utils.PageDesc;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * TemplateFile  Controller.
 * create by scaffold 2018-05-17 
 * @author 脚手架，改成开发者的名字
 * C_TEMPLATE_FILEnull   
*/


@Controller
@RequestMapping("/doc/templatefile")
public class TemplateFileController  extends BaseController {
	private static final Log log = LogFactory.getLog(TemplateFileController.class);
	
	@Resource
	private TemplateFileManager templateFileMag;
	@Resource
    private DataDictionaryManager dataDictionaryManager;

    /**
     * 查询所有   C_TEMPLATE_FILE  列表
     *
     * @param field    json中只保存需要的属性名
     * @param request  {@link HttpServletRequest}
     * @param response {@link HttpServletResponse}
     * @return {data:[]}
     */
    @RequestMapping(method = RequestMethod.GET)
    public void list(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> searchColumn = convertSearchColumn(request);
        String limit=request.getParameter("limit");//必要写法
        pageDesc.setPageSize(Integer.parseInt(limit));//设置参数
        //searchColumn.put("isused", "T");
        JSONArray jsonArrayObjects = templateFileMag.listObjectsAsJson( searchColumn, pageDesc);
        if (null == pageDesc) {
            JsonResultUtils.writeSingleDataJson(jsonArrayObjects, response);
            return;
        }
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, jsonArrayObjects);
        resData.addResponseData(PAGE_DESC, pageDesc);
        layuiResultUtil.layuiwriteResponseDataAsJson(resData, pageDesc, response);
    }
    
    /**
     * 查询单个  C_TEMPLATE_FILE 
	
	 * @param recordid  recordid
     *  
     * 
     * @param response    {@link HttpServletResponse}
     * @return {data:{}}
     */
    @RequestMapping(value = "/{recordid}", method = {RequestMethod.GET})
    public void getTemplateFile(@PathVariable String recordid, HttpServletResponse response) {
    	
    	TemplateFile templateFile =
    			templateFileMag.getObjectById( recordid);
        
        JsonResultUtils.writeSingleDataJson(templateFile, response);
    }
    

    /**
     * 删除单个  C_TEMPLATE_FILE 
	
	 * @param recordid  recordid
     */
    @RequestMapping(value = "/isused/{recordid}", method = {RequestMethod.POST})
    public void deleteTemplateFile(@PathVariable String recordid, HttpServletResponse response) {
        templateFileMag.deleteObjectById(recordid);
        JsonResultUtils.writeSingleDataJson("操作成功",response);
    }
    /**
     * 复制单个  C_TEMPLATE_FILE

     * @param recordid  recordid
     */
    @RequestMapping(value = "/copy/{recordid}", method = {RequestMethod.POST})
    public void copyTemplateFile(@PathVariable String recordid, HttpServletResponse response) {
        TemplateFile templateFile=templateFileMag.getObjectById(recordid);
        if(templateFile!=null){
            templateFile.setRecordid(UuidOpt.getUuidAsString32());
            templateFile.setFiledate(new Date());
            templateFileMag.saveNewObject(templateFile);
            JsonResultUtils.writeSingleDataJson("复制成功",response);
        }else{
            JsonResultUtils.writeSingleDataJson("模板不存在，复制失败",response);
        }


    }

    /**
     * 新增或保存 C_TEMPLATE_FILE 
	 * @param templateFile  {@link TemplateFile}
     * @param response    {@link HttpServletResponse}
     */
    @RequestMapping(value = "/save", method = {RequestMethod.POST})
    public void updateTemplateFile(@Valid TemplateFile templateFile,HttpServletRequest request, HttpServletResponse response) {
    	TemplateFile dbTemplateFile  =
    			templateFileMag.getObjectById(templateFile.getRecordid()==null?"":templateFile.getRecordid());
        if (null != dbTemplateFile) {//如果数据库数据存在，则是更新操作
        	dbTemplateFile .copyNotNullProperty(templateFile);//赋值页面不为空的值，小心页面空的字符串或者改写copyNotNullProperty方法，根据自己业务需要
        	//templateFileMag.mergeObject(dbTemplateFile);
        } else {
            templateFile.setRecordid(UuidOpt.getUuidAsString32());
            // templateFileMag.saveNewObject(templateFile);//新增,注意主键赋值 UuidUtil.getTimeBasedUuid()，填写自己的业务时间，业务操作人等信息
        }

       // JsonResultUtils.writeSingleDataJson("操作成功",response);
    }

    /**
     * 跳转到金格编辑页面
     *
     * @return
     */
    @RequestMapping(value = "/toDocumentEdit",method = {RequestMethod.GET})
    public void toDocumentEdit(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("X-Frame-Options", "SAMEORIGIN");// 解决IFrame拒绝的问题
        String templeteId="";
        String mDescript="";
        String mFileName="";
        //自动获取OfficeServer和OCX文件完整URL路径
        String mHttpUrlName=request.getRequestURI();
        String mScriptName=request.getServletPath();
        String mServerName="OfficeServer";
        String mServerUrl="http://"+request.getServerName()+":"+request.getServerPort()+mHttpUrlName.substring(0,mHttpUrlName.lastIndexOf(mScriptName))+"/"+mServerName;//取得OfficeServer文件的完整URL
        String mRecordID=request.getParameter("RecordID");
        String mTemplate = request.getParameter("Template");
        String mFileType=".doc";
        String tempType=request.getParameter("tempType");
        String mEditType="1,1";
        String mUserName="Administrator";
        String orderBy = "";
        String codeCode = "";
        //取得模式
        if (mEditType==null)
        {
            mEditType="2,1";		//2 起草
        }
        //取得类型
        if ( mFileType==null)
        {
            mFileType=".doc";	// 默认为.doc文档
        }
        //取得用户名
        if (mUserName==null)
        {
            mUserName="";
        }
        //取得模板
        if ( mRecordID==null)
        {
            mRecordID="";	// 默认没有模板
        }
        TemplateFile templateFile=templateFileMag.getObjectById(mRecordID);

        JSONObject docJson=new JSONObject();
        docJson.put("mServerUrl",mServerUrl);
        docJson.put("mRecordID",mRecordID);
        docJson.put("mTemplate",mTemplate);
        docJson.put("mFileType",mFileType);
        docJson.put("mEditType",mEditType);
        docJson.put("mUserName",mUserName);
        docJson.put("mDescript",mDescript);
        request.setAttribute("docJson",docJson);
        request.setAttribute("templateFile",templateFile);
        try {
           request.getRequestDispatcher("/modules/templatefile/template-edit.jsp").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开金格
     * WebUrl:系统服务器路径，与服务器文件交互操作，如保存、打开文档，重要文件
     *
     * @return
     */
    @RequestMapping(value = "/officeServer",method = {RequestMethod.POST})
    public void officeServer(HttpServletRequest request, HttpServletResponse response) {

    }

    /**
     *数据字典
     *
     *
     * @return
     */
    @RequestMapping(value = "/dic",method = {RequestMethod.GET})
    public void dic(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> searchColumn = convertSearchColumn(request);
        List<DataDictionary> dicjson=dataDictionaryManager.listDataDictionarys(searchColumn);
        //catalogcode
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, dicjson);
        JsonResultUtils.writeResponseDataAsJson(resData, response);
    }
}
